package com.rran.study.designpattern.factory.singleton.lazy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author yy
 * @Type GoodDCLLazySingleton.java
 * @Desc DCL懒汉单例模式最终版 推荐使用
 * @date 2020/7/23 10:16
 */
public class GoodDCLLazySingleton {
    private static volatile GoodDCLLazySingleton instance;

    private GoodDCLLazySingleton() {
        //如果通过反射访问到构造方法，也要判断一下，如果实例存在就抛异常
        if (instance != null) {
            throw new IllegalStateException("Already initialized.");
        }
    }

    public static GoodDCLLazySingleton getInstance() {
        GoodDCLLazySingleton result = instance;
        if (result == null) {
            //如果实例是空的，就加锁
            synchronized (GoodDCLLazySingleton.class) {
                //如果实例还是空的，就new一个，然后返回；
                result = instance;
                if (result == null) {
                    instance = result = new GoodDCLLazySingleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        GoodDCLLazySingleton instance = GoodDCLLazySingleton.getInstance();
        GoodDCLLazySingleton instance1 = GoodDCLLazySingleton.getInstance();
        System.out.println("instance hashcode:"+instance.hashCode());
        System.out.println("instance1 hashcode:"+instance1.hashCode());
        Constructor<GoodDCLLazySingleton> constructor = GoodDCLLazySingleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        GoodDCLLazySingleton reflectInstance = constructor.newInstance();
        System.out.println("reflectInstance hashcode:"+reflectInstance.hashCode());
    }
}
